#include "picker_tray.h"
#include "game_engine.h"
#include "battle_scene.h"
#include "dude.h"
#include "SDL_gfx/SDL_rotozoom.h"
#include <string>
#include <sstream>
#include "progress_bar.h"

#define PICKER_BOTTOM_CLEARANCE 40
#define PICKER_BUTTON_CLEARANCE 80
#define PICKER_MAX_DUDES 5

PickerTray::PickerTray(Player &myPlayer)
	: RenderTarget(myPlayer.side == PLAYER_LEFT ? "picker_left" : "picker_right"), player(myPlayer)
{

	//Constant data of side/index -> key shortcut
	SDLKey leftShortcuts[] = { SDLK_q, SDLK_w, SDLK_a, SDLK_s, SDLK_z, SDLK_x };
	SDLKey rightShortcuts[] = { SDLK_RIGHTBRACKET, SDLK_LEFTBRACKET, SDLK_QUOTE, SDLK_SEMICOLON, SDLK_SLASH, SDLK_PERIOD };

	Sprite *panel = new Sprite("UI_P1_troop_pane.png", true);
	if (player.side == PLAYER_LEFT)
	{
		panel->setPosition(-500, 768 - panel->getRenderImage()->h - PICKER_BOTTOM_CLEARANCE); //+ 100
		panel->setDestPosition(0, 768 - panel->getRenderImage()->h - PICKER_BOTTOM_CLEARANCE);
	}
	else
	{
		panel->setResource("UI_P2_troop_pane.png", true);
		panel->setPosition(1024 - panel->getRenderImage()->w + 500, 768 - panel->getRenderImage()->h - PICKER_BOTTOM_CLEARANCE); //+ 100
		panel->setDestPosition(1024 - panel->getRenderImage()->w, 768 - panel->getRenderImage()->h - PICKER_BOTTOM_CLEARANCE);
	}
	panel->setMoveSpeed(500);
	panel->setZOrder(0);
	addChild(panel);

	//Add a button for each member on the team up to 6 (not dynamic yet)
	for (int i = 0; i < player.team.members.size() && i < PICKER_MAX_DUDES; i++)
	{
		double x = 50 + 98 * i;

		//Initialize buttons
		Button *button = new Button("button-96.png", &PickerTray::staticButtonClick, this);
		if (player.side == PLAYER_LEFT)
		{
			button->setPosition(x, 50); //768 - 50  - PICKER_BUTTON_CLEARANCE);
			button->setDestPosition(x, 50); //768 - 50 - PICKER_BUTTON_CLEARANCE);
			button->hotKey = leftShortcuts[i];
		}
		else
		{
			button->setPosition(panel->getRenderImage()->w - x, 50); //(1024 - x, 768 - 50 - PICKER_BUTTON_CLEARANCE); 
			button->setDestPosition(panel->getRenderImage()->w - x, 50); //(1024 - x, 768 - 50 - PICKER_BUTTON_CLEARANCE);
			button->hotKey = rightShortcuts[i];
		}

		//Create string of index, and save as a property of the button
		std::stringstream tag;
		tag << i;
		button->getIdComp()->setProperty("templateId", tag.str());
		//Set z order and relativism
		button->setZOrder(500);
		button->setRelativeToParent(true);
		panel->addChild(button);

		//Get double size avatar
		double avatar_y = 0.0;
		std::string revName = player.team.members.at(i).baseResourceName + ":2x";
		SDL_Surface* image = GameEngine::getResources()->GetImage(revName, true);
		if (image == NULL) //Reverse image not setup in res. manager
		{
			SDL_Surface *orig = GameEngine::getResources()->GetImage(player.team.members.at(i).baseResourceName, true);
			double factorX = 90.0 / orig->w; //, factorY = 90.0 / orig->h;
			image = zoomSurface(orig, factorX, 2, 0);
			GameEngine::getResources()->SetImage(revName, image);
		}

		avatar_y = 42 - (image->h / 2);

		Sprite *icon = new Sprite(revName, true);
		icon->centered = true;
		icon->setRelativeToParent(true);
		icon->setZOrder(100);
		icon->setPosition(0, avatar_y);
		icon->setDestPosition(0, avatar_y);
		button->addChild(icon);

		ProgressBar *progress = new ProgressBar("picker_progress_empty.png", "picker_progress_ready.png");
		progress->getIdComp()->id = "progress";
		progress->centered = true;
		progress->setPosition(0, 41);
		progress->setDestPosition(0, 41);
		progress->setZOrder(50);
		progress->setRelativeToParent(true);
		button->addChild(progress);

		button->SetEnabled(false);
		Timer *coolTimer = new Timer(0.7);
		coolTimer->set_repeat(true);
		coolTimer->set_callback(PickerTray::staticProgressUpdate, button);
		GameEngine::getInstance()->addTimer(coolTimer);
	}
}

void PickerTray::staticButtonClick(void *obj, Button *button)
{
	if (obj != NULL)
	{
		PickerTray *tray = (PickerTray*)obj;
		tray->ButtonClick(button);
		/*
		button->SetEnabled(false);
		Timer *coolTimer = new Timer(0.7);
		coolTimer->set_repeat(true);
		coolTimer->set_callback(PickerTray::staticProgressUpdate, button);
		GameEngine::getInstance()->addTimer(coolTimer);
		*/
	}
}

void PickerTray::ButtonClick(Button *button)
{
	if (button == NULL)
		return;

	int templateId = -1;
	
	BattleScene *battle = dynamic_cast<BattleScene*>(GameEngine::getInstance()->findSceneById("battle_scene"));
	ProgressBar *progress = dynamic_cast<ProgressBar*>(button->findChildWithId("progress"));

	//If battle was found
	if (battle != NULL && progress != NULL)
	{
		//Get number of this button to get correct template number
		std::string templateIdStr = button->getIdComp()->getProperty("templateId");
		if (templateIdStr.compare("") != 0)
		{
			templateId = atoi(templateIdStr.c_str());

			if (templateId > -1 && templateId < player.team.members.size() && templateId < PICKER_MAX_DUDES)
			{
				//disable button
				button->SetEnabled(false);
				//Set cool down timer up
				Timer *coolTimer = new Timer(0.7);
				coolTimer->set_repeat(true);
				coolTimer->set_callback(PickerTray::staticProgressUpdate, button);
				GameEngine::getInstance()->addTimer(coolTimer);

				Dude* dude = new Dude(*battle, player.side, player.team.members.at(templateId));

				if (!battle->AddDude(dude))
				{
					delete dude;
					dude = NULL;
				}
				else
				{
					progress->percentProgress = 0.0;
				}
			}
		}
	}
}


void PickerTray::staticProgressUpdate(void *obj, Timer *timer)
{
	bool stopTimer = false;

	Button *button = (Button*)obj;
	if (button != NULL && button->getParent() != NULL)
	{
		ProgressBar *progress = dynamic_cast<ProgressBar*>(button->findChildWithId("progress"));
		PickerTray *picker = dynamic_cast<PickerTray*>(button->getParent()->getParent());

		if (progress != NULL && picker != NULL)
		{
			//Get which template this button is for
			int templateId = -1;

			//Get number of this button to get correct template number
			std::string templateIdStr = button->getIdComp()->getProperty("templateId");
			if (templateIdStr.compare("") != 0)
			{
				//Convert string to int
				templateId = atoi(templateIdStr.c_str());

				//If template is within the proper range, advance progress
				if (templateId > -1 && templateId < picker->player.team.members.size() && templateId < PICKER_MAX_DUDES)
				{
					//Use stats of dude to cool down at the right rate
					progress->percentProgress += 100.0 / picker->player.team.members.at(templateId).stats.getBuildTime();
					if (progress->percentProgress >= 100.0)
					{
						progress->percentProgress = 100.0;
						timer->set_repeat(false); //No longer repeat
						button->SetEnabled(true); //Re-enable button
					}
				}
				else
					stopTimer = true;
			}
			else
				stopTimer = true;
		}
		else
			stopTimer = true;
	}
	else
		stopTimer = true;

	if (stopTimer)
	{
		timer->set_repeat(false); //Didn't have a valid id or button structure, stop repeating
	}
}